package com.ruoyi.projectAch.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.projectAch.domain.AchievementInfo;
import com.ruoyi.projectAch.domain.AchievementQueryParams;
import com.ruoyi.projectAch.domain.Data;
import com.ruoyi.projectAch.domain.Result.SchoolNameAndLevel;
import com.ruoyi.projectAch.service.impl.AchievementInfoServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RequestMapping("/api")
@RestController
public class AchievementController {

    @Autowired
    private AchievementInfoServiceImpl achievementInfoService;

    @PostMapping("/getList")
    public List list(@RequestBody AchievementInfo achievementInfo) throws IllegalAccessException {
        //被标记的学校
       List<AchievementInfo> list = achievementInfoService.selectSchoolName(achievementInfo);

        Map<String, Integer> countMap = new HashMap<>();
        for (AchievementInfo info : list) {
            String schoolName = info.getSchoolName();
            countMap.put(schoolName, countMap.getOrDefault(schoolName, 0) + 1);
        }

        List<Map<String, Object>> result = new ArrayList<>();
        for (Map.Entry<String, Integer> entry : countMap.entrySet()) {
            String name = entry.getKey();
            int value = entry.getValue();
            Map<String, Object> item = new HashMap<>();
            item.put("name", name);
            item.put("value", value);
            result.add(item);
        }
        return result;
    };


    @PostMapping("/getLevel")
    public List<SchoolNameAndLevel> getLevel(@RequestBody AchievementInfo achievementInfo){
        List<SchoolNameAndLevel> achievementInfoList = achievementInfoService.selectLevel(achievementInfo);
        System.out.println(achievementInfoList);
        return achievementInfoList;
    }


    @PostMapping ("/data")
    public ResponseEntity<Data> getAchievementData(@RequestBody AchievementQueryParams queryParams) {
        Data data = achievementInfoService.getAchievementsData(queryParams.getStartTime(), queryParams.getEndTime());
        return ResponseEntity.ok(data);
    }


    @PostMapping("/getLevelTotal")
    public List<Map<String, Object>> getTotal(@RequestBody(required = false) Map<String, Object> params) {
        String schoolName = params != null ? (String) params.get("schoolName") : null;
        String startTime = params != null ? (String) params.get("startTime") : null;
        String endTime = params != null ? (String) params.get("endTime") : null;

        List<Map<String, Object>> list = achievementInfoService.selectTotal(schoolName, startTime, endTime);

        return list;
    }


}
